package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.result.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class UploadController {
    @Value("${tanhua.oss.endpoint}")
    private String endpoint;
    @Value("${tanhua.oss.accessKey}")
    private String accessKeyId;
    @Value("${tanhua.oss.secret}")
    private String accessKeySecret;
    @Value("${tanhua.oss.bucketName}")
    private String bucketName;
    @Value("${tanhua.oss.url}")
    private String url;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + UUID.randomUUID().toString() + suffixName;
        OSS ossclient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossclient.putObject(bucketName, filename, inputStream);
        ossclient.shutdown();
        String ossUrl = url  + filename;
        return R.success(ossUrl);
    }
}
